//
//  NSString+WHTest.m
//  WHDocKit
//
//  Created by wangpeng on 2020/11/5.
//  Copyright © 2020 wellhope. All rights reserved.
//

#import "NSString+WHTest.h"
#import <sys/xattr.h>
#import <CommonCrypto/CommonDigest.h>

@implementation NSString (WHTest)

- (NSString *)convertToFileIDFromFilePath
{
	// 计算fileID
	NSDictionary *attrDict = [[NSFileManager defaultManager] attributesOfItemAtPath:self error:nil];
	NSTimeInterval creationTime = [[attrDict objectForKey:NSFileCreationDate] timeIntervalSince1970];
	NSString *relativePath = nil;
	NSRange range = [self rangeOfString:@"/Documents/"];
	if (range.location != NSNotFound && range.length > 0) {
		relativePath = [self substringFromIndex:(range.location+range.length)];
	} else {
		relativePath = self;
	}
	NSString *fileId = [NSString stringWithFormat:@"%@, %lf", relativePath, creationTime];
	NSString *fileID = [fileId wh_md5HashString];
	return fileID;
}

- (NSString *)wh_md5HashString
{
	return [self wh_md5HashStringByEncoding:NSUTF8StringEncoding];
}

- (NSString *)wh_md5HashStringByEncoding:(NSStringEncoding)encoding
{
	const char *ptr = [self cStringUsingEncoding:encoding];
	unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
	CC_MD5(ptr, (int)strlen(ptr), md5Buffer);
	NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
	for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
		[output appendFormat:@"%02x",md5Buffer[i]];
	}
	
	return output;
}

@end
